package com.sdap2.service.impl;

import com.sdap2.common.dao.LogicDAO;
import com.sdap2.common.exception.BusinessException;
import com.sdap2.common.service.impl.BaseService;
import com.sdap2.dao.GreenhouseDAO;
import com.sdap2.dao.DeviceDAO;
import com.sdap2.dao.SoilDataDAO;
import com.sdap2.dao.CameraDataDAO;
import com.sdap2.dto.GreenhouseDTO;
import com.sdap2.entity.Greenhouse;
import com.sdap2.entity.SysUser;
import com.sdap2.entity.Device;
import com.sdap2.service.GreenhouseService;
import com.sdap2.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class GreenhouseServiceImpl extends BaseService<Greenhouse> implements GreenhouseService {
    
    private final GreenhouseDAO greenhouseDAO;
    private final DeviceDAO deviceDAO;
    private final SoilDataDAO soilDataDAO;
    private final CameraDataDAO cameraDataDAO;
    private final SysUserService sysUserService;
    
    @Override
    protected LogicDAO<Greenhouse, Long> getRepository() {
        return greenhouseDAO;
    }
    
    @Override
    @Transactional
    public Greenhouse create(GreenhouseDTO dto, String token) {
        SysUser currentUser = sysUserService.getCurrentUser(token);
        if (currentUser == null) {
            throw new BusinessException("用户未登录");
        }
        
        // 检查boxNo是否已存在
        if (greenhouseDAO.existsByBoxNo(dto.getBoxNo())) {
            throw new BusinessException("大棚编号已存在");
        }
        
        Greenhouse greenhouse = new Greenhouse();
        BeanUtils.copyProperties(dto, greenhouse);
        greenhouse.setUser(currentUser);
        greenhouse.setStatus(1); // 默认启用
        
        return greenhouseDAO.save(greenhouse);
    }
    
    @Override
    @Transactional
    public Greenhouse update(Long id, GreenhouseDTO dto, String token) {
        Greenhouse greenhouse = getById(id, token);
        
        // 如果修改了boxNo，需要检查是否与其他大棚冲突
        if (!greenhouse.getBoxNo().equals(dto.getBoxNo())) {
            if (greenhouseDAO.existsByBoxNo(dto.getBoxNo())) {
                throw new BusinessException("大棚编号已存在");
            }
        }
        
        // 保持原有的用户和状态不变
        String oldBoxNo = greenhouse.getBoxNo();
        Integer oldStatus = greenhouse.getStatus();
        SysUser oldUser = greenhouse.getUser();
        
        BeanUtils.copyProperties(dto, greenhouse);
        
        // 恢复不允许修改的字段
        greenhouse.setBoxNo(oldBoxNo); // 不允许修改boxNo
        greenhouse.setStatus(oldStatus);
        greenhouse.setUser(oldUser);
        
        return greenhouseDAO.save(greenhouse);
    }
    
    @Override
    @Transactional
    public void delete(Long id, String token) {
        Greenhouse greenhouse = getById(id, token);
        
        // 1. 查找该温室下的所有设备
        List<Device> devices = deviceDAO.findAllByGreenhouseId(id);
        
        // 2. 删除每个设备相关的数据
        for (Device device : devices) {
            switch (device.getDeviceType()) {
                case SOIL_MOISTURE:
                case SOIL_TEMPERATURE:
                    // 删除土壤数据
                    soilDataDAO.deleteByDeviceId(device.getId());
                    break;
                case CAMERA:
                    // 删除摄像头数据
                    cameraDataDAO.deleteByDeviceId(device.getId());
                    break;
            }
        }
        
        // 3. 删除设备
        deviceDAO.deleteAllByGreenhouseId(id);
        
        // 4. 最后删除温室
        greenhouseDAO.deleteById(id);
    }
    
    @Override
    public Greenhouse getById(Long id, String token) {
        SysUser currentUser = sysUserService.getCurrentUser(token);
        if (currentUser == null) {
            throw new BusinessException("用户未登录");
        }
        
        Greenhouse greenhouse = greenhouseDAO.findById(id)
                .orElseThrow(() -> new BusinessException("大棚不存在"));
                
        if (!greenhouse.getUser().getId().equals(currentUser.getId())) {
            throw new BusinessException("无权操作此大棚");
        }
        
        return greenhouse;
    }
    
    @Override
    public Page<Greenhouse> getPage(Pageable pageable, String token) {
        SysUser currentUser = sysUserService.getCurrentUser(token);
        if (currentUser == null) {
            throw new BusinessException("用户未登录");
        }
        
        return greenhouseDAO.findAllByUserId(currentUser.getId(), pageable);
    }
    
    @Override
    @Transactional
    public Greenhouse updateAccessToken(Long id, String accessToken, String token) {
        Greenhouse greenhouse = getById(id, token);
        greenhouse.setAccessToken(accessToken);
        return greenhouseDAO.save(greenhouse);
    }
    
    @Override
    public Greenhouse getByBoxNo(String boxNo, String token) {
        SysUser currentUser = sysUserService.getCurrentUser(token);
        if (currentUser == null) {
            throw new BusinessException("用户未登录");
        }
        
        Greenhouse greenhouse = greenhouseDAO.findByBoxNo(boxNo)
                .orElseThrow(() -> new BusinessException("大棚不存在"));
                
        if (!greenhouse.getUser().getId().equals(currentUser.getId())) {
            throw new BusinessException("无权操作此大棚");
        }
        
        return greenhouse;
    }
} 